	export default {
		name: "imgpicker",
		props: {
            modelValue: {
                type: String,
                default: ''
            },
            uploadurl: {
                type: String,
                default: () => window.APP_CONFIG?.baseurl + 'v1/dbupload'
            },
            size: {
                type: String,
                default: 'medium',
                validator: (v) => ['medium', 'small'].includes(v)
            }
		},
		setup(props, {emit}) {
		    const { smartSpeak } = inject('speech'); //语音
			const dialogVisible = ref(false);
			const imageList = ref([]);
			const loading = ref(false);
			const currentPage = ref(1);
			const pageSize = ref(12);
			const total = ref(0);
			const noMore = ref(false);
			const fileInput = ref(null);
			const baseurl = window.APP_CONFIG.baseurl;
            const currentFolder = ref(localStorage.getItem('imgpicker_currentFolder') || 'blog');
            const folderList = ref({blog: '公告', bjt: '背景图', ico: '图标', template: '网页模板', sc: '素材',});
            
            // 选择文件夹
            const onFolderChange = () => {
                currentPage.value = 1;
                total.value = 0;
                noMore.value = false;
                imageList.value = [];
                debounceLoad();
            };
            
            // 获取图片列表
			const loadImages = async () => {
				if (loading.value || noMore.value) return
				loading.value = true
				const res = await getimglist({page: currentPage.value, pageSize: pageSize.value, folder: currentFolder.value});
				const newList = res.items.map(item => ({
					id: item.id,
					url: item.url.startsWith('http') ? item.url : `${baseurl}${item.url}`
				}))
				imageList.value = currentPage.value === 1 ? newList : [...imageList.value, ...newList];
				total.value = res.total
				noMore.value = imageList.value.length >= res.total;
				currentPage.value++;
				loading.value = false;
			}
			
			// 加防抖
			const debounceLoad = _.debounce(loadImages, 100);

			const showPicker = () => {
				dialogVisible.value = true
			}

			const closePicker = () => {
				dialogVisible.value = false
			}

			const handleDelete = () => {
				emit('update:modelValue', '')
			}

			const handleSelect = (item) => {
				emit('update:modelValue', item.url)
				closePicker()
			}

            //上传
			const triggerUpload = () => {
			    if(!currentFolder.value) return ElMessage.error('文件夹不得为空');
				fileInput.value.click()
			}

			const handleFileChange = async (e) => {
				const file = e.target.files[0]
				if (!file) return
				if (file.size > 10 * 1024 * 1024) {
					return ElMessage.error('图片大小不能超过10M')
				}
				if(!currentFolder.value) return ElMessage.error('文件夹不得为空');
				const formData = new FormData()
				formData.append('file', file)
				formData.append('name', 'file')
				formData.append('path', currentFolder.value); // 添加文件夹参数
				try {
					const response = await axios.post(props.uploadurl, formData, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					const newImage = {
						id: response.data.data.id,
						url: response.data.data.url || ''
					}
					imageList.value.unshift(newImage)
					emit('update:modelValue', newImage.url)
				} catch (error) {
					ElMessage.error('上传失败')
				} finally {
					e.target.value = ''
				}
			}

			const deleteImage = async (item) => {
				try {
					await ElMessageBox.confirm('确定要永久删除这张图片吗？', '确认删除', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					if (!item?.id) {
                        throw new Error('无效的图片ID');
                    }
					await deleteimg(item);
					imageList.value = imageList.value.filter(i => i.id !== item.id)
					if (props.modelValue === item.url) {
						emit('update:modelValue', '')
					}
				} catch (error) {
					// 取消删除不处理
				}
			}

			const loadMore = () => {
				if (!loading.value && !noMore.value) debounceLoad()
			}
			
            const handleDialogOpened = () => {
                if (imageList.value.length === 0) {
                    debounceLoad();
                }
            }
            
            watch(currentFolder, (newVal) => {
                localStorage.setItem('imgpicker_currentFolder', newVal);
            });

            return {
                dialogVisible,
                imageList,
                loading,
                currentPage,
                pageSize,
                total,
                noMore,
                fileInput,
                baseurl,
                loadImages,
                showPicker,
                closePicker,
                handleDelete,
                handleSelect,
                triggerUpload,
                handleFileChange,
                deleteImage,
                loadMore,
                currentFolder,
                folderList,
                onFolderChange,
                debounceLoad,
                handleDialogOpened
            };
		},
        
    template: `
	<div class="single-image-picker">
		<!-- 预览区域 -->
		<div v-if="size=='small'">
		    <div v-if="modelValue" style="width:60px;height:70px;position: relative;">
				<img :src="modelValue" class="preview-image small" />
				<el-icon style="position: absolute;right: 1px;top: 1px;background: rgba(0, 0, 0, 0.5);padding: 2px;border-radius: 50%;color: white;z-index: 2;" @click.stop="handleDelete">
					<Delete :size="12"/>
				</el-icon>
			</div>
			<div v-else class="upload-trigger" :class="size">
				<el-icon @click="showPicker" :size="25"><Picture /></el-icon>
			</div>
		</div>
		<div class="preview-wrapper" :class="size" @click="showPicker" v-else>
			<div v-if="modelValue" class="preview-content" :class="size">
				<img :src="modelValue" class="preview-image" />
				<el-icon class="delete-btn" @click.stop="handleDelete">
					<Delete />
				</el-icon>
			</div>
			<div v-else class="upload-trigger" :class="size">
				<el-icon class="camera-icon"><Camera /></el-icon>
				<span class="tip-text">选择图片</span>
			</div>
		</div>

		<!-- 选择弹窗 -->
		<el-dialog v-model="dialogVisible" custom-class="image-picker-dialog" :show-close="false" @opened="handleDialogOpened" :append-to-body="true">
			<template #header>
				<div class="dialog-header">
					<div class="header-left">
						<span class="title">选择图片</span>
                        <div style="position: relative;width: 240px;">
                            <el-select v-model="currentFolder" placeholder="选择文件夹" @change="onFolderChange">
                                <el-option v-for="(name, key) in folderList" :key="key" :label="name" :value="key"/>
                            </el-select>
                        </div>
						<el-button type="success" plain @click="triggerUpload">
							<el-icon>
								<Upload />
							</el-icon>
							<span>上传</span>
						</el-button>
					</div>
					<el-icon class="close-icon" @click="closePicker">
						<Close />
					</el-icon>
				</div>
			</template>

			<div v-infinite-scroll="loadMore" class="image-grid" :infinite-scroll-disabled="loading || noMore">
				<div class="grid-container">
					<div v-for="item in imageList" :key="item.id" class="grid-item" :class="{ selected: modelValue === item.url }" @click="handleSelect(item)">
						<img :src="item.url" class="thumbnail" />
						<div class="item-actions">
							<div v-if="modelValue === item.url" class="selected-mark">
								<el-icon color="#fff"><Select /></el-icon>
							</div>
							<div class="delete-action" @click.stop="deleteImage(item)">
								<el-icon color="#fff">
									<Delete />
								</el-icon>
							</div>
						</div>
					</div>
				</div>

				<div v-if="loading" class="loading-text">加载中...</div>
				<div v-if="noMore" class="loading-text">没有更多了</div>
			</div>
		</el-dialog>

		<input ref="fileInput" type="file" accept="image/*" hidden @change="handleFileChange" />
	</div>
    `
}